import pymongo
from pymongo import MongoClient

#
# import streamlit as st
# import pandas as pd
# from io import StringIO
#
# # 应用标题
# st.title("可编辑表格应用")
# st.write("在此应用中，您可以编辑表格数据并下载保存修改后的内容。")
#
# # 初始化session_state中的dataframe
# if 'df' not in st.session_state:
#     # 创建示例数据
#     sample_data = pd.DataFrame({
#         '姓名': ['张三', '李四', '王五'],
#         '年龄': [25, 30, 35],
#         '城市': ['北京', '上海', '广州'],
#         '职业': ['工程师', '设计师', '产品经理']
#     })
#     st.session_state.df = sample_data
#
# # 侧边栏 - 数据管理选项
# with st.sidebar:
#     st.header("数据管理")
#
#     # 上传文件选项
#     uploaded_file = st.file_uploader("上传CSV文件", type=['csv'])
#     if uploaded_file is not None:
#         # 读取上传的文件
#         df_uploaded = pd.read_csv(uploaded_file)
#         st.session_state.df = df_uploaded
#         st.success("数据已成功加载！")
#
#     # 重置为示例数据
#     if st.button("重置为示例数据"):
#         sample_data = pd.DataFrame({
#             '姓名': ['张三', '李四', '王五'],
#             '年龄': [25, 30, 35],
#             '城市': ['北京', '上海', '广州'],
#             '职业': ['工程师', '设计师', '产品经理']
#         })
#         st.session_state.df = sample_data
#         st.rerun()
#
#     # 添加新行
#     if st.button("添加新行"):
#         new_row = pd.DataFrame({col: [""] for col in st.session_state.df.columns})
#         st.session_state.df = pd.concat([st.session_state.df, new_row], ignore_index=True)
#         st.rerun()
#
#     st.divider()
#     st.info("使用说明：\n1. 直接点击表格单元格进行编辑\n2. 完成后点击下方下载按钮保存")
#
# # 主界面 - 显示可编辑表格
# st.header("编辑表格数据")
# edited_df = st.data_editor(
#     st.session_state.df,
#     num_rows="dynamic",  # 允许动态添加/删除行
#     use_container_width=True,
#     height=400
# )
#
# # 更新session_state中的数据
# st.session_state.df = edited_df
#
# # 显示数据统计信息
# st.subheader("数据概览")
# col1, col2, col3 = st.columns(3)
# col1.metric("总行数", len(edited_df))
# col2.metric("总列数", len(edited_df.columns))
# col3.metric("数据总量", f"{len(edited_df) * len(edited_df.columns)}")
#
# # 下载功能
# st.subheader("下载数据")
# # 将DataFrame转换为CSV
# csv = edited_df.to_csv(index=False)
# # 创建下载按钮
# st.download_button(
#     label="下载为CSV文件",
#     data=csv,
#     file_name="edited_data.csv",
#     mime="text/csv"
# )
#
# # 显示当前数据
# with st.expander("查看当前数据"):
#     st.dataframe(edited_df, use_container_width=True)

#
# import streamlit as st
#
# st.title("左右布局示例")
#
# # 创建列
# col1, col2 = st.columns(2)
#
# with col1:
#     st.subheader("休息人员名单")
#     rest_names_input = st.text_input(
#         "请输入休息人员姓名，多个姓名用逗号分隔，例如丁冬，杨军",
#         key="rest_names"
#     )
#
# with col2:
#     st.subheader("休息车辆名单")
#     rest_car_numbers_input = st.text_input(
#         "请输入休息车辆的车牌号，多个车牌号用逗号分隔，例如湘AM9210，湘AK1377",
#         key="rest_car_numbers"
#     )
#
# # 处理逻辑（可以在任意位置）
# if rest_names_input:
#     st.session_state.staff['rest_names'] = [name.strip() for name in rest_names_input.split("，")]
# else:
#     st.session_state.staff['rest_names'] = []
#
# if rest_car_numbers_input:
#     st.session_state.staff['rest_car_numbers'] = [number.strip() for number in rest_car_numbers_input.split("，")]
# else:
#     st.session_state.staff['rest_car_numbers'] = []
#
# # 在下方显示结果
# st.subheader("结果展示")
# st.json(st.session_state.staff)
#
#
#




























# ----------------------
# MongoDB数据加载
# ----------------------
MONGO_URI = "mongodb://172.40.10.127:27017/"
DB_NAME = "innerVehicle"
VEH_COLL = "vehicle_test"
DRV_COLL = "driver_test"
client = MongoClient(MONGO_URI)
db = client[DB_NAME]
db_update = client[DB_NAME]
collection = db_update['vehicle']

# delete_filter = {"tpye": "10.5米挂车"}
# result = collection.update_many(delete_filter,{"$set": {'plate_number':'湘AT456挂'}})
#
# print(f"删除了 {result.deleted_count} 条13米挂车记录")

new_vehicles=[
    {
        'vehicle_id':18,
        'type':'10.5米挂车',
        'plate_number':'湘AM087挂'
    },
    {
        'vehicle_id': 19,
        'type': '13米挂车',
        'plate_number': '湘AN775挂'
    },
    {
        'vehicle_id': 20,
        'type': '13米挂车',
        'plate_number': '湘AN786挂'
    },
    {
        'vehicle_id': 21,
        'type': '13米挂车',
        'plate_number': '湘AL492挂'
    },
    {
        'vehicle_id': 22,
        'type': '13米挂车',
        'plate_number': '湘AT456挂'
    }
]

# 插入多条数据
result = collection.insert_many(new_vehicles)
print(f"插入成功，文档IDs: {result.inserted_ids}")

# import streamlit as st
# import json
#
# st.title("货物与人员信息输入系统")
# st.write("请填写以下信息，用于生成今日任务数据")
#
# # 初始化session state
# if 'cargo' not in st.session_state:
#     st.session_state.cargo = {
#         '铝卷': {'count': None},
#         '铝棒': {'load_times': None},
#         '单顶': {'load_times': None},
#         '双零箔': {
#             'count': None,
#             'size_breakdown': {
#                 'four_point_two': None,
#                 'ten_point_five': None,
#                 'thirteen': None
#             }
#         },
#         '废铝卷': {
#             'count': None,
#             'scania': None,
#             'benz': None
#         }
#     }
#
# if 'staff' not in st.session_state:
#     st.session_state.staff = {
#         'name': None,
#         'rest_names': []
#     }
#
# if 'payload' not in st.session_state:
#     st.session_state.payload = {
#         'rest_car_numbers': []
#     }
#
# # 创建选项卡
# tab1, tab2, tab3 = st.tabs(["货物信息", "人员信息", "车辆信息"])
#
# with tab1:
#     st.header("货物信息")
#
#     with st.expander("铝卷信息"):
#         col1, col2 = st.columns(2)
#         with col1:
#             st.session_state.cargo['铝卷']['count'] = st.number_input(
#                 "铝卷数量", min_value=0, key="aluminum_roll_count"
#             )
#         with col2:
#             discard_shuai_count = st.number_input(
#                 "甩挂铝卷数量", min_value=0, key="discard_shuai_count"
#             )
#             discard_count = st.number_input(
#                 "废弃铝卷数量", min_value=0, key="discard_count"
#             )
#
#     with st.expander("铝棒信息"):
#         st.session_state.cargo['铝棒']['load_times'] = st.number_input(
#             "铝棒装载次数", min_value=0, key="aluminum_bar_times"
#         )
#
#     with st.expander("单顶信息"):
#         st.session_state.cargo['单顶']['load_times'] = st.number_input(
#             "单顶装载次数", min_value=0, key="single_top_times"
#         )
#
#     with st.expander("双零箔信息"):
#         st.session_state.cargo['双零箔']['count'] = st.number_input(
#             "双零箔总数", min_value=0, key="double_zero_count"
#         )
#
#         st.subheader("尺寸细分")
#         col1, col2, col3 = st.columns(3)
#         with col1:
#             st.session_state.cargo['双零箔']['size_breakdown']['four_point_two'] = st.number_input(
#                 "4.2尺寸数量", min_value=0, key="four_point_two"
#             )
#         with col2:
#             st.session_state.cargo['双零箔']['size_breakdown']['ten_point_five'] = st.number_input(
#                 "10.5尺寸数量", min_value=0, key="ten_point_five"
#             )
#         with col3:
#             st.session_state.cargo['双零箔']['size_breakdown']['thirteen'] = st.number_input(
#                 "13尺寸数量", min_value=0, key="thirteen"
#             )
#
#         load_time = st.time_input("装载时间", value=None, key="load_time")
#
#     with st.expander("废铝卷信息"):
#         st.session_state.cargo['废铝卷']['count'] = st.number_input(
#             "废铝卷总数", min_value=0, key="waste_aluminum_count"
#         )
#         col1, col2 = st.columns(2)
#         with col1:
#             st.session_state.cargo['废铝卷']['scania'] = st.number_input(
#                 "斯堪尼亚废铝卷数量", min_value=0, key="scania_waste"
#             )
#         with col2:
#             st.session_state.cargo['废铝卷']['benz'] = st.number_input(
#                 "奔驰废铝卷数量", min_value=0, key="benz_waste"
#             )
#
# with tab2:
#     st.header("人员信息")
#
#     st.session_state.staff['name'] = st.text_input(
#         "常德甩挂人员姓名", key="staff_name"
#     )
#
#     st.subheader("休息人员名单")
#     rest_names_input = st.text_area(
#         "请输入休息人员姓名，多个姓名用逗号分隔", key="rest_names"
#     )
#     if rest_names_input:
#         st.session_state.staff['rest_names'] = [name.strip() for name in rest_names_input.split(",")]
#     else:
#         st.session_state.staff['rest_names'] = []
#
# with tab3:
#     st.header("车辆信息")
#
#     st.subheader("休息车辆")
#     rest_car_input = st.text_area(
#         "请输入休息车辆车牌号，多个车牌用逗号分隔", key="rest_cars"
#     )
#     if rest_car_input:
#         st.session_state.payload['rest_car_numbers'] = [car.strip() for car in rest_car_input.split(",")]
#     else:
#         st.session_state.payload['rest_car_numbers'] = []
#
# # 生成结果
# st.divider()
# st.header("生成的数据结构")
#
# # 构建today_tasks
# today_tasks = {
#     '铝卷': {
#         'count': st.session_state.cargo.get('铝卷', {}).get('count'),
#         'discard_shuai_count': discard_shuai_count,
#         'discard_count': discard_count,
#     },
#     '铝棒': {
#         'times': st.session_state.cargo.get('铝棒', {}).get('load_times')
#     },
#     '单顶': {
#         'times': st.session_state.cargo.get('单顶', {}).get('load_times')
#     },
#     '双零箔': {
#         'count': st.session_state.cargo.get('双零箔', {}).get('count'),
#         'four_point_two': st.session_state.cargo.get('双零箔', {}).get('size_breakdown', {}).get('four_point_two'),
#         'ten_point_five': st.session_state.cargo.get('双零箔', {}).get('size_breakdown', {}).get('ten_point_five'),
#         'thirteen': st.session_state.cargo.get('双零箔', {}).get('size_breakdown', {}).get('thirteen'),
#         'load_time': load_time.strftime("%H:%M") if load_time else None
#     },
#     '废铝卷': {
#         'count': st.session_state.cargo.get('废铝卷', {}).get('count'),
#         'scania': st.session_state.cargo.get('废铝卷', {}).get('scania'),
#         'benz': st.session_state.cargo.get('废铝卷', {}).get('benz')
#     },
#     '常德甩挂人员': {
#         'name': st.session_state.staff.get('name')
#     },
#     '长沙甩挂人员': {
#         'name': '刘锦红'
#     },
#     '休息人员名单': {
#         'rest_names': st.session_state.staff.get('rest_names')
#     },
#     '休息车辆': {
#         'rest_car_numbers': st.session_state.payload.get('rest_car_numbers')
#     }
# }
#
# # 显示生成的数据
# st.json(today_tasks)
#
# # 下载按钮
# json_data = json.dumps(today_tasks, ensure_ascii=False, indent=2)
# st.download_button(
#     label="下载JSON数据",
#     data=json_data,
#     file_name="today_tasks.json",
#     mime="application/json"
# )
#
#















# def calculate_driver_start_time(driver_info,task):
#     if driver_info == '常德':
#         return task['load_time']
#     if driver_info == '长沙':
#         if task['cargo_type'] in ['双零箔','废铝/铝卷']:
#             return task['departure_time']
#         else:
#             return minutes_to_time(time_to_minutes(task['load_time'])-210)
#     return None
# # # 只为尚未有 end_time 字段的文档添加
# result = collection.insert_many(
#     [
#         {'driver_id': 'M1','driver_name':'李胜果','health':'true','is_intern':'false','last_4days_departure_times':['12:00','12:00','12:00','12:00'],'month_double_zero_count':0,'region':'长沙','season_single_top_count':5,'end_time':'14:00'},
#         {'driver_id': 'M19','driver_name':'刘锦红','health':'true','is_intern':'false','last_4days_departure_times':['12:00','12:00','12:00','12:00'],'month_double_zero_count':0,'region':'长沙','season_single_top_count':5,'end_time':'14:00'}
#     ]
# )
# result= collection.delete_one({
#     'driver_id':'M19'
# })
#
#
#













# from pymongo import UpdateOne
#
# # 定义要删除的字段
# fields_to_delete = [
#     "available_for_aluminum_bar",
#     "available_for_aluminum_roll",
#     "available_for_double_zero",
#     "available_for_single_top"
# ]
#
# # 使用批量写入操作提高性能
# batch_size = 1000
# batch_operations = []
#
# # 遍历所有文档并创建更新操作
# cursor = collection.find({})
# for doc in cursor:
#     # 检查文档中是否存在这些字段
#     existing_fields = [field for field in fields_to_delete if field in doc]
#     if existing_fields:
#         unset_dict = {field: "" for field in existing_fields}
#         batch_operations.append(
#             UpdateOne(
#                 {"_id": doc["_id"]},
#                 {"$unset": unset_dict}
#             )
#         )
#
#     # 批量执行
#     if len(batch_operations) >= batch_size:
#         result = collection.bulk_write(batch_operations)
#         batch_operations = []
#         print(f"已处理 {batch_size} 个文档")
#
# # 处理剩余的批量操作
# if batch_operations:
#     result = collection.bulk_write(batch_operations)
#     print(f"处理完成，总共处理了文档")
#
# print("所有指定字段已成功删除")
# # 为所有文档添加 region 字段，值为 '长沙'
# result = collection.update_many(
#     {},  # 空过滤器表示匹配所有文档
#     {"$set": {"region": "长沙"}}  # 设置 region 字段的值为 '长沙'
# )
#
# print(f"成功更新了 {result.modified_count} 个文档")

# # 使用 update_many 重命名字段
# result = collection.update_many(
#     {},  # 空过滤器表示匹配所有文档
#     {'$rename': {"available": "end_time"}}
# )



#
#
# def generate_a_schedule(today_tasks, schedule, vehicles, start_window=(360, 720), end_window=(840, 1080), interval=30):
#     A_count = today_tasks['铝卷']['count'] - today_tasks['废铝卷']['count']
#     scania_benz = [v for v in vehicles if v['type'] in ['SCANIA', '奔驰']]
#     available_a_vehicles = [v for v in scania_benz if not v['used']]
#     transfer_count = max(0, A_count - len(available_a_vehicles))
#     a_vehicles = available_a_vehicles[:A_count]
#     a_tasks = []
#     used_times = set()
#     current_time = start_window[0]
#     for vehicle in a_vehicles:
#         if current_time > start_window[1]:
#             break
#         time_str = minutes_to_time(current_time)
#         if current_time not in used_times:
#             vehicle['available_time'] = current_time
#             a_tasks.append({'type': '铝卷', 'time': time_str, 'vehicle_id': vehicle['id']})
#             used_times.add(current_time)
#         current_time += interval
#     for i in range(min(transfer_count, len(a_vehicles))):
#         vehicle = a_vehicles[i]
#         morning_time = vehicle['available_time']
#         transfer_time = max(morning_time + 540, end_window[0])
#         if transfer_time > end_window[1]:
#             continue
#         transfer_time_str = minutes_to_time(transfer_time)
#         a_tasks.append({'type': '铝卷', 'time': transfer_time_str, 'vehicle_id': vehicle['id']})
#     for task in a_tasks:
#         selected = next((v for v in vehicles if v['id'] == task['vehicle_id']), None)
#         if selected:
#             schedule.append({
#                 'driver_name': '', 'plate_number': '', 'vehicle_id': selected['id'],
#                 'vehicle_type': selected['type'], 'departure_time': task['time'],
#                 'load_time': calculate_load_time(task['time'], '铝卷'), 'cargo_type': task['type'],
#                 'is_transfer': '否'
#             })
#             selected['available_time'] = time_to_minutes(task['time'])
#             selected['used'] = True
#         else:
#             print('时间为', task['time'], '的', task['type'], '无车辆可安排')
#
#     return schedule
#
# import pymongo
# from pymongo import MongoClient
# from datetime import datetime
# import re
#
# # ----------------------
# # MongoDB连接配置
# # ----------------------
# MONGO_URI = "mongodb://172.40.10.127:27017/"
# DB_NAME = "innerVehicle"
# client = MongoClient(MONGO_URI)
# db = client[DB_NAME]
# collection = db['driver_test']  # 修改为你要操作的集合
#
#
# def convert_to_datetime(value):
#     """
#     将各种格式的时间字符串转换为datetime对象
#     """
#     if value is None:
#         return None
#
#     if isinstance(value, datetime):
#         return value
#
#     elif isinstance(value, str):
#         # 移除可能的空格
#         value = value.strip()
#
#         # 尝试解析常见的时间格式
#         try:
#             # ISO格式: "2023-10-15T14:30:00" 或 "2023-10-15T14:30:00.000Z"
#             if 'T' in value:
#                 if value.endswith('Z'):
#                     return datetime.fromisoformat(value.replace('Z', '+00:00'))
#                 else:
#                     return datetime.fromisoformat(value)
#
#             # 日期时间格式: "2023-10-15 14:30:00"
#             elif re.match(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', value):
#                 return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
#
#             # 日期格式: "2023-10-15"
#             elif re.match(r'\d{4}-\d{2}-\d{2}', value):
#                 return datetime.strptime(value, '%Y-%m-%d')
#
#             # 时间戳格式 (毫秒或秒)
#             elif value.isdigit():
#                 timestamp = int(value)
#                 # 判断是秒还是毫秒时间戳
#                 if timestamp > 10000000000:  # 毫秒时间戳 (通常大于10^10)
#                     return datetime.fromtimestamp(timestamp / 1000)
#                 else:  # 秒时间戳
#                     return datetime.fromtimestamp(timestamp)
#
#         except (ValueError, TypeError) as e:
#             print(f"转换失败: {value}, 错误: {e}")
#             return None
#
#     # 如果是数字但不是字符串形式的数字
#     elif isinstance(value, (int, float)):
#         try:
#             if value > 10000000000:  # 毫秒时间戳
#                 return datetime.fromtimestamp(value / 1000)
#             else:  # 秒时间戳
#                 return datetime.fromtimestamp(value)
#         except (ValueError, TypeError) as e:
#             print(f"数字转换失败: {value}, 错误: {e}")
#             return None
#
#     # 如果无法转换，返回None
#     return None
#
#
# def convert_end_time_to_datetime():
#     """
#     将end_time字段转换为时间类型
#     """
#     try:
#         print("开始转换end_time字段为时间类型...")
#
#         # 获取所有包含end_time字段的文档
#         docs_with_end_time = collection.find({"end_time": {"$exists": True}})
#         total_count = collection.count_documents({"end_time": {"$exists": True}})
#         converted_count = 0
#         failed_count = 0
#
#         print(f"找到 {total_count} 个包含end_time字段的文档")
#
#         for i, doc in enumerate(docs_with_end_time, 1):
#             doc_id = doc['_id']
#             current_value = doc.get('end_time')
#
#             if i % 1000 == 0 or i == total_count:
#                 print(f"处理进度: {i}/{total_count}")
#
#             # 转换时间格式
#             datetime_value = convert_to_datetime(current_value)
#
#             if datetime_value:
#                 # 更新文档
#                 collection.update_one(
#                     {'_id': doc_id},
#                     {'$set': {'end_time': datetime_value}}
#                 )
#                 converted_count += 1
#             else:
#                 print(f"文档 {doc_id} 的end_time字段无法转换为时间类型: {current_value} (类型: {type(current_value)})")
#                 failed_count += 1
#                 # 可以选择删除无效数据或设置为null
#                 # collection.update_one(
#                 #     {'_id': doc_id},
#                 #     {'$set': {'end_time': None}}
#                 # )
#
#         print(f"转换完成!")
#         print(f"- 成功转换: {converted_count} 个文档")
#         print(f"- 转换失败: {failed_count} 个文档")
#         print(f"- 总计处理: {total_count} 个文档")
#
#         return {
#             "total_count": total_count,
#             "converted_count": converted_count,
#             "failed_count": failed_count
#         }
#
#     except Exception as e:
#         print(f"处理过程中发生错误: {e}")
#         return None
#
#
# def verify_conversion():
#     """
#     验证转换结果
#     """
#     print("\n验证转换结果:")
#
#     # 检查转换后的数据类型
#     sample_docs = collection.find({"end_time": {"$exists": True, "$type": "date"}}).limit(5)
#     date_count = collection.count_documents({"end_time": {"$exists": True, "$type": "date"}})
#
#     print(f"成功转换为时间类型的文档数量: {date_count}")
#     print("样例数据:")
#
#     for i, doc in enumerate(sample_docs, 1):
#         field_value = doc.get('end_time')
#         print(f"文档 {i}: end_time = {field_value} (类型: {type(field_value)})")
#
#
# def create_index_on_end_time():
#     """
#     在end_time字段上创建索引以提高查询性能
#     """
#     try:
#         print("\n在end_time字段上创建索引...")
#         collection.create_index([("end_time", pymongo.ASCENDING)])
#         print("索引创建成功")
#     except Exception as e:
#         print(f"索引创建失败: {e}")
#
#
# # 执行处理
# if __name__ == "__main__":
#     # 执行类型转换
#     result = convert_end_time_to_datetime()
#
#     if result:
#         # 验证转换结果
#         verify_conversion()
#
#         # 创建索引
#         create_index_on_end_time()
#
#     # 关闭连接
#     client.close()


# import pymongo
# from pymongo import MongoClient
#
# # ----------------------
# # MongoDB连接配置
# # ----------------------
# MONGO_URI = "mongodb://172.40.10.127:27017/"
# DB_NAME = "innerVehicle"
# client = MongoClient(MONGO_URI)
# db = client[DB_NAME]
# collection = db['driver_test']  # 修改为你要操作的集合
#
#
# def delete_available_field():
#     """
#     删除所有文档中的available字段
#     """
#     try:
#         print("开始删除available字段...")
#
#         # 统计包含available字段的文档数量
#         count_with_available = collection.count_documents({"available": {"$exists": True}})
#         print(f"找到 {count_with_available} 个包含available字段的文档")
#
#         # 使用update_many删除available字段
#         result = collection.update_many(
#             {"available": {"$exists": True}},  # 只匹配包含available字段的文档
#             {"$unset": {"available": ""}}  # 删除available字段
#         )
#
#         print(f"成功从 {result.modified_count} 个文档中删除了available字段")
#
#         # 验证删除结果
#         remaining_count = collection.count_documents({"available": {"$exists": True}})
#         print(f"删除后，仍有 {remaining_count} 个文档包含available字段")
#
#         return result.modified_count
#
#     except Exception as e:
#         print(f"删除过程中发生错误: {e}")
#         return 0
#
#
# # 执行删除操作
# if __name__ == "__main__":
#     deleted_count = delete_available_field()
#     print(f"\n操作完成! 总共删除了 {deleted_count} 个文档中的available字段")
#     client.close()
#
#

